package com.test.nio.channel;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ReadFile {

    public static void main(String args[]){
        try {
            //随机读写文件
            RandomAccessFile accessFile = new RandomAccessFile("H:\\robots.txt","rw");
            //文件通道
            FileChannel inChannel = accessFile.getChannel();
            //分配128字节capacity的ByteBuffer
            ByteBuffer buf = ByteBuffer.allocate(128);
            int bytesRead = 0;
            try {
                bytesRead = inChannel.read(buf);

                while (bytesRead != -1) {
                    //System.out.println("Read " + bytesRead);
                    //切换到读入模式
                    buf.flip();
                    while(buf.hasRemaining()) {
                        System.out.print((char) buf.get());
                    }
                    //清空buf
                    buf.clear();
                    //读取到buf
                    bytesRead = inChannel.read(buf);
                }
                //写入到文件
                //accessFile.write("成功".getBytes("UTF-8"));
                accessFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}
